import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_elec_price_setting_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/enums.dart';

class EnergyStoreageDischargePriceController extends GetxController with GetTickerProviderStateMixin {
    bool isEnableEdit = false;
    int? id;
    late int   siteId;
    SiteElecPriceSettingModel model = SiteElecPriceSettingModel();
    SiteServices siteServices = Get.put(SiteServices());
    RefreshController refreshController = RefreshController(
        initialRefresh: false,
    );
    List<String> titleStringList = [ResKey.basicInfo.tr,ResKey.siteSettingEffectiveDate.tr,ResKey.siteSettingElectricityStagePrice.tr,];
    final TextEditingController ruleNameController = TextEditingController();
    final DeviceServices services = Get.put(DeviceServices());
    List<dynamic> timeDateList = [ {
        'effectiveTime':'01-01',
        'expirationTime':'12-31',
    }];
    List<dynamic> stagePriceList = [
        {
            "intervalStartTime": "00:00",
            "intervalEndTime": "24:00",
            "electricityFees": "1",
            "elecType": "0"
        },
    ];

    int status = 1;
    bool isEnableCommit = false;
    bool isAdd = true;
    @override
    void onInit() {
    super.onInit();
    if (Get.arguments != null) {
        if(Get.arguments['siteId'] != null){
            siteId = Get.arguments['siteId'];

        }
        if(Get.arguments['id'] != null){
            id = Get.arguments['id'];
            ///id 无则是新增
            isAdd = false;
        }
        if(Get.arguments['isEnableEdit'] != null){
            isEnableEdit = Get.arguments['isEnableEdit'];
        }
    }
    }

    @override
    void onReady() {
        if(id != null){
            if (refreshController.isRefresh) {
                refreshController.refreshCompleted();
            }
            loadData(refereshType: RefereshType.load);
        }
    }

    @override
    void onClose() {}

    void edit() {
        isEnableEdit = true;
        update();
    }

    /// 请求站点-储能详情数据
    Future<void> loadData(
        {RefereshType refereshType = RefereshType.refresh}) async {
        Configs.httpClient.requestWithLoading(
                () async {
                var params = {'id': id};
                var data = await siteServices.getSiteInternetDetail(params);
                var temp = SiteElecPriceSettingModel.fromJson(data);
                model = temp;
                ruleNameController.text = model.name!;
                status = model.status!;
                checkCommitStatus();
                if(model.effectiveTimeList != null){
                    timeDateList.clear();
                    for (var element in model.effectiveTimeList!) {
                        timeDateList.add(
                            {
                                "effectiveTime": element.effectiveTime,
                                "expirationTime": element.expirationTime,
                            }
                        );
                    }
                }
                if(model.hoursPriceList != null){
                    stagePriceList.clear();
                    for (var element in model.hoursPriceList!) {
                        stagePriceList.add(
                            { "intervalStartTime": element.intervalStartTime,
                                "intervalEndTime": element.intervalEndTime,
                                "electricityFees": element.electricityFees,
                                'elecType':element.elecType
                            }
                        );
                    }
                }
                update();
            },
            onError: (error) {
                refreshController.loadFailed();
                showError(error.message);
                return true;
            },
        );
    }

    ///下一步按钮是否可以点击
    checkCommitStatus() {
        if(ruleNameController.text.isNotEmpty&& timeDateList.isNotEmpty && stagePriceList.isNotEmpty){
            isEnableCommit = true;
        }else{
            isEnableCommit = false;
        }
        update();
    }

    void updateTimeList(){
        timeDateList.addAll([ {
            "effectiveTime": "01-01",
            "expirationTime": "12-31"
        }]);
        checkCommitStatus();
        update();
    }

    void deleteTimeList(int index){
        timeDateList.removeAt(index);
        checkCommitStatus();
        update();
    }

    void updateStagePriceList(){
        stagePriceList.addAll([ {
            "intervalStartTime": "00:00",
            "intervalEndTime": "24:00",
            "electricityFees": "1",
            'elecType':'0'
        }]);
        checkCommitStatus();
        update();
    }

    void deleteStagePriceList(int index){
        stagePriceList.removeAt(index);
        checkCommitStatus();
        update();
    }

    Future<void> save() async {
        var param = {
            "name": ruleNameController.text,
            "status": status,
            "siteId": siteId,
            'type':'1',
            'id':id
        };
        if(timeDateList.isNotEmpty){
            param['effectiveTimeList'] = timeDateList;
        }
        if(stagePriceList.isNotEmpty){
            param['hoursPriceList'] = stagePriceList;
        }
        showLoading(toast:ResKey.loading.tr);
        if(isAdd){
            var result = await services.sitePhotovoltaicAdd(param,onError: (p0) {
                dismissLoading();
                handleException(p0);
                return false;
            },);
            dismissLoading();
            Log.d('result==' + result.toString());
            if(result==true){
                Get.back(result: true);
            }
        }else{
            param['siteId'] = siteId;
            Log.d('param==' + param.toString());
            var result = await services.sitePhotovoltaicAUpdate(param,onError: (p0) {
                dismissLoading();
                handleException(p0);
                return false;
            },);
            dismissLoading();
            Log.d('result==' + result.toString());
            if(result==true){
                Get.back(result: true);
            }
        }

    }

    void cancelEdit(){
        Log.d('cancelEdit==');
        if(id == null){
            Get.back();
        }else{
            isEnableEdit = false;
            update();
        }

    }
}
